import { addBannerApi } from '@/services/banner';
import { PageContainer } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Button, Form, Image, Input, message } from 'antd';
import { useState } from 'react';

const AccessPage: React.FC = () => {
  const [img, setImg] = useState('');
  const [messageApi, contextHolder] = message.useMessage();

  const onFinish = async (values: any) => {
    const res = await addBannerApi({ ...values, img });
    if (res) {
      messageApi.open({
        type: 'success',
        content: res.message,
      });
      history.push('/banner/list');
    }
  };

  const fn = (e: any) => {
    // console.log(e.target.files[0]);
    // 要将图片转成base64,不用记的
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = (event: any) => {
      setImg(event.target.result);
    };
  };

  return (
    <PageContainer
      ghost
      header={{
        title: '添加轮播图',
      }}
    >
      {contextHolder}
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="链接"
          name="link"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="提示"
          name="alt"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="图片"
          name="img"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input type="file" onChange={fn} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>

        {img && (
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Image src={img} alt="" width={200} />
          </Form.Item>
        )}
      </Form>
    </PageContainer>
  );
};

export default AccessPage;
